package com.wjk.controller;

import com.wjk.exception.UserException;
import com.wjk.pojo.Role;
import com.wjk.pojo.User;
import com.wjk.service.RoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @author: RobertWei
 * time: 2021/8/12    11:08
 * @TODO:
 */

@RequestMapping("permission")
@Controller
public class PermissionController {


    @Autowired
    private RoleService roleService;


    @RequiresPermissions(value = "权限分配")
    @GetMapping("grant")
    public String grant(HttpServletRequest request){
        //查询所有角色

        List<Role> roles = roleService.findAll();

        request.setAttribute("roles",roles);

        return "permission/grant";
    }

    @RequiresPermissions(value = "权限赋权")
    @GetMapping("change")
    public String change(String[] roles, HttpSession session) throws UserException {

        //roles  -->  存储了角色的id

        //1.用户角色的中间表, 根据用户uid删除所有数据

        Map<String,Object> data = (Map<String, Object>) session.getAttribute("data");

        User user = (User) data.get("user");

        System.out.println("user = " + user);

        int uId = user.getuId();

        int rows = roleService.removeAllRoles(uId);

        if (rows == 0){
            throw new UserException("权限移除失败");
        }

        //2.roleid和用户id,去中间表中插入数据

        for (String role : roles) {
            int rId = Integer.parseInt(role);
            rows= roleService.addRole(uId,rId);
            if (rows == 0){
                throw new UserException("权限添加失败");
            }
        }

        //3.修改完之后返回重新登陆

        return "login";
    }


}
